package com.hyg.lib_music.ui.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_music.R;
import com.hyg.lib_music.databinding.FragmentShuimianRecommendBinding;
import com.hyg.lib_music.modle.RecommedMusicData;
import com.hyg.lib_music.ui.activity.MainMusicBedActivity;
import com.hyg.lib_music.ui.activity.MusicMainActivity;
import com.hyg.lib_music.ui.activity.MusicPlayingDetailActivity;
import com.hyg.lib_music.ui.activity.PlayingListActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class RecommendShuimianFragment extends Fragment {

    MusicMainActivity activity;
    List<RecommedMusicData.DataDTO> list15;
    List<RecommedMusicData.DataDTO> list20;
    List<RecommedMusicData.DataDTO> list40;

    ArrayList<Music> music_list15=new ArrayList<>();
    ArrayList<Music> music_list20=new ArrayList<>();
    ArrayList<Music> music_list40=new ArrayList<>();

    FragmentShuimianRecommendBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentShuimianRecommendBinding.inflate(inflater, container, false);
        activity= (MusicMainActivity) getActivity();
        EventBus.getDefault().register(this);
        init();
        return binding.getRoot();
    }

    public void init() {
        initView();
        initData();
    }

    public void initView() {
        binding.itemControl1.tvControlIntro.setText("15min");
        binding.itemControl2.tvControlIntro.setText("20min");
        binding.itemControl3.tvControlIntro.setText("40min");
        binding.itemControl1.tvControlTitle.setText("助眠定制方案");
        binding.itemControl2.tvControlTitle.setText("助眠定制方案");
        binding.itemControl3.tvControlTitle.setText("助眠定制方案");
        Glide.with(getActivity()).load(R.mipmap.zhumian_music_icon).into(binding.itemControl1.ivControlImage);
        Glide.with(getActivity()).load(R.mipmap.zhumian_music_icon).into(binding.itemControl2.ivControlImage);
        Glide.with(getActivity()).load(R.mipmap.zhumian_music_icon).into(binding.itemControl3.ivControlImage);
//        binding.itemControl1.cvRoot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(list15!=null && list15.size()>0){
//                    ToPlayActivity(music_list15);
//                }else{
//                    Toast.makeText(activity, "未发现音乐列表！", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
        binding.itemControl1.lnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startMusicPlaying(music_list15);
            }
        });
//          binding.itemControl2.cvRoot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(list20!=null && list20.size()>0){
//                    ToPlayActivity(music_list20);
//                }else{
//                    Toast.makeText(activity, "未发现音乐列表！", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
        binding.itemControl2.lnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startMusicPlaying(music_list20);
            }
        });

//        binding.itemControl3.cvRoot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(list40!=null && list40.size()>0){
//                    ToPlayActivity(music_list40);
//                }else{
//                    Toast.makeText(activity, "未发现音乐列表！", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
        binding.itemControl3.lnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startMusicPlaying(music_list40);
            }
        });
    }

    private void initData() {
        getMusicListData(1);
        getMusicListData(2);
        getMusicListData(3);
    }

    private void getMusicListData(int type) {
        CommonHttpUtil.getHealthMusic(getActivity(), 2, type, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.ErrorDialog("服务器错误");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse: "+result);
                parseData(result, type);
            }
        });
    }


    public void parseData(String data, int type) {
        RecommedMusicData musicData = JSONObject.parseObject(data, RecommedMusicData.class);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (musicData.getCode() == 200) {
                    if (type == 1) {
                        list15 = musicData.getData();
                        music_list15=changeToMusicList(list15,1);
                    } else if (type == 2) {
                        list20 = musicData.getData();
                        music_list20=changeToMusicList(list20,1);
                    } else if (type == 3) {
                        list40 = musicData.getData();
                        music_list40=changeToMusicList(list40,1);
                    }
                } else {
                    activity.ErrorDialog(musicData.getMessage());
                }
            }
        });
    }


    private void ToPlayActivity(ArrayList<Music> list) {
        Intent intent=new Intent(getActivity(), PlayingListActivity.class);
        intent.putParcelableArrayListExtra("data", list);
        startActivity(intent);
    }


    public ArrayList<Music> changeToMusicList(List<RecommedMusicData.DataDTO> list,int sleepMusicType){
        ArrayList<Music> music_list = new ArrayList<>();
        for (RecommedMusicData.DataDTO dataDTO : list) {
            music_list.add( new Music(dataDTO.getId(), dataDTO.getMusicName(), dataDTO.getMusician(), dataDTO.getMusicDuration(),
                    dataDTO.getRegion(), dataDTO.getMusicUrl(), (dataDTO.getFavorite()==1),
                    2,sleepMusicType, "",
                    (MusicMainActivity.serviceBinder.isPlaying() && MusicMainActivity.serviceBinder.getCurrentMusic().musicName.equals(dataDTO.musicName)),
                    false,false));
        }
        return music_list;
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.i("lgb", "onResume: shuimina");

    }


    public void startMusicPlaying(ArrayList<Music> list){
        if (list != null && list.size() > 0 && MusicMainActivity.serviceBinder != null) {
            MusicMainActivity.serviceBinder.setImagePath(R.mipmap.zhumian_music_icon);
            startActivity(new Intent(getActivity(), MusicPlayingDetailActivity.class));
            MusicMainActivity.serviceBinder.addPlayList(list, list.get(0));
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(EventBusMessage message) {
        Log.i("lgb", "onEvent shuimian: "+message.getmessage());
       if(message.getmessage().equals(Constants.Add_Favorite)){
           Log.i("lgb", "onEvent:shuimian id= "+message.getMusicId());
            for(Music music:music_list15){

                if( music.id==message.getMusicId()){
                    music.isFav=true;
                }
            }
            for(Music music:music_list20){
                if( music.id==message.getMusicId()){
                    music.isFav=true;
                }
            }
            for(Music music:music_list40){
                if( music.id==message.getMusicId()){
                    music.isFav=true;
                }
            }
        }else if(message.getmessage().equals(Constants.Cancel_Favorite)){
                for(Music music:music_list15){
                    if( music.id==message.getMusicId()){
                        music.isFav=false;
                    }
                }
                for(Music music:music_list20){
                    if( music.id==message.getMusicId()){
                        music.isFav=false;
                    }
                }
                for(Music music:music_list40){
                    if( music.id==message.getMusicId()){
                        music.isFav=false;
                    }
                }
            }
        }

}